import Taro from "@tarojs/taro";

/**
 * 将字符串转换成ArrayBufer
 */
export function string2buffer(str) {
  if (!str) return;
  var val = "";
  for (var i = 0; i < str.length; i++) {
    val += str.charCodeAt(i).toString(16);
  }
  console.log(val);
  str = val;
  val = "";
  let length = str.length;
  let index = 0;
  let array = []
  while (index < length) {
    array.push(str.substring(index, index + 2));
    index = index + 2;
  }
  val = array.join(",");
  // 将16进制转化为ArrayBuffer
  return new Uint8Array(val.match(/[\da-f]{2}/gi).map(function (h) {
    return parseInt(h, 16)
  })).buffer
}
/**
 * 将ArrayBuffer转换成字符串
 */
export function ab2hex(buffer) {
  var hexArr = Array.prototype.map.call(
    new Uint8Array(buffer),
    function (bit) {
       return ('00' + bit.toString(16)).slice(-2)
    }
  )
  // 转字符串
  // const encodedString = String.fromCodePoint.apply(null, hexArr)
  // console.log('获取数据为：', encodedString)
 
  return hexArr.join('');
}

/**
        * 16进制转换为字符串
        * @param hex
        * @returns {*}
        */
export function hexToString(hex) {
  var tmp = '';
  if (hex.length % 2 == 0) {
    for (var i = 0; i < hex.length; i += 2) {
      tmp += '%' + hex.charAt(i) + hex.charAt(i + 1);
    }
  }
  return decodeURIComponent(tmp);
}


export function rgbToHex(r, g, b) {
  let hex = ((r << 16) | (g << 8) | b).toString(16)
  if (hex.length < 6) {
    hex = `${'0'.repeat(6-hex.length)}${hex}`
  }
  if (hex == '0') {
    hex = '000000'
  }
  return `#${hex}`
}

/**
 * 判断传值是否为空、[]、{}
 * @param {*} param 
 * @returns 
 */
export const isEmpty = (param) => {
  if (param == null) {
    return true;
  } else if (typeof param === 'string') {
    return param == '';
  } else if (typeof param === 'object') {
    return JSON.stringify(param) == '[]' || JSON.stringify(param) == '{}';
  }
  return false;
}

